import router from '@/router'
import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor  请求拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      // if (Date.now() - localStorage.getItem('time') > 1000 * 60 * 60 * 4) {
      //   store.dispatch('user/logOut')
      //   router.push('/login')
      //   return Promise.reject('登录超时，请重新登录！')
      // }
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
  }
)

// response interceptor  响应拦截器
service.interceptors.response.use(
  res => {
    const { success, message, data } = res.data
    if (success) {
      return data
    } else {
      Message.error(message)
      return Promise.reject()
    }
  },
  err => {
    console.dir(err)
    if (err.response && err.response.data.code === 10002) {
      store.dispatch('user/logOut')
      router.push('/login')
      Message.error('登录超时，请重新登录！')
    } else {
      console.log(err)
      Message.error(err.typeOf === 'string' ? err : '系统繁忙，请稍后！')
    }
    return Promise.reject(err)
  }
)

// 暴露实例
export default service

